/**
 *  使用优惠劵
 */
define(function(require,exports,module) {
    var myPub = require('./public');

    var oShadow = $('.js_shadow');				        //阴影
    var oCouponSeletSide = $('.js_couponSeletSide');    //优惠劵领取弹框
    var oUseCoupon = $('.js_useCoupon');                //优惠劵列表展示按钮-商品详情页面
    var oGoodsCoupon = $('.js_goodsCoupon');            //详情优惠劵框
    var oMoreBtnBox = $('.js_moreBtnBox');              // 显示没有了 或者加载中的按钮
    var oCoupSwiper = $('.js_coupSwiper');              // swiper区域的高度
    var oCouponList = $('.js_couponList');              // 优惠券列表的高度
    var timer = null;
    var bTapOff = true;                                 // 点击领取优惠券时防止重复点击
    var tap_timer = null;                               // 防止重复点击定时器

    var moveHeight = oCouponSeletSide.outerHeight(true);    //物品详情优惠劵高度
    oCouponSeletSide.css({'bottom': -moveHeight });


    var oCloseBtn = $('.js_closeBtn');
    var bSideOff = true;
    var loadAll = false;  //判断是否成功请求过优惠券

    // var oGetNow = $('.js_getNow');   //立即领取
    var NavName = ['店铺券','平台券'];
    // 物品详情优惠劵领取
    oUseCoupon.hammer().on('tap', function () {
        if(!bSideOff)  return;
        bSideOff = false;
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(false);
        }



        oCouponSeletSide.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
            if(couponArea.bSwiperLoadOff[couponArea.busDetailNum]){                 // 已经点过 再点击就不加载数据了
                couponArea.bSwiperLoadOff[couponArea.busDetailNum] = false;         // 已经点过 再点击就不加载数据了
                couponArea.getDeatilData(couponArea.busDetailNum);                  // 加载数据
                couponArea.oswiperSlidMain.slideTo(couponArea.busDetailNum, 100);   // 滑动到缓存页面
            }
        });


        clearTimeout(timer);
        timer = setTimeout(function () {
            bSideOff = true
        },250);


        myPub.HamstopPropaga();
    });

    // 阴影点击关闭
    oShadow.hammer().on('tap', function () {
        //隐藏服务
        oCouponSeletSide.stop().animate({bottom:-moveHeight},300,function(){
            oCouponSeletSide.hide();
            oShadow.hide();
            // bSideOff = true
        });
        myPub.HamstopPropaga();
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

    });

    oCloseBtn.hammer().on('tap', function () {
        //隐藏服务
        oCouponSeletSide.stop().animate({bottom:-moveHeight},300,function(){
            oCouponSeletSide.hide();
            oShadow.hide();
            // bSideOff = true
        });
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

        myPub.HamstopPropaga();
    });



    //立即领取
    function getNow() {
        // 立即领取操作
        $('.js_getNow').hammer().off('tap');
        $('.js_getNow').hammer().on('tap', function (e) {
            if(bTapOff){
                bTapOff = false;
                e.stopPropagation();
                var _tarTag = e.gesture.target;
                var target;
                target = $(_tarTag);
                if(_tarTag.nodeName.toLowerCase() == 'button') {
                    var couponId = e.currentTarget.dataset.couponid;
                    G_JSON_GET('/coupon/drawSupplierCoupon',{couponId: couponId},function (data) {
                        if(data.status == 'success'){
                            myPub.TipLayer(data.message);
                            target.hide().next().show();
                            if(typeof mui !== 'undefined'){

                                myPub.OffMuiEvent(true);
                            }
                        }else {

                            myPub.TipLayer(data.message);
                        }
                    })

                    // oCouponSeletSide.stop().animate({bottom:-moveHeight},300,function(){
                    //     oCouponSeletSide.hide();
                    //     oShadow.hide();
                    //     bSideOff = true;
                    // });
                    // target.hide().next().show();
                    // if(typeof mui !== 'undefined'){
                    //     myPub.OffMuiEvent(true);
                    // }
                }

                myPub.HamstopPropaga();
            }

            clearTimeout(tap_timer);
            tap_timer = setTimeout(function () {
                bTapOff = true;
            },250)
        });
    }

    var couponArea = {
        paggerr:[1,1],                       // 页码数
        startNum:[0,0],                      // 开始加载时的数据
        limit:5,                            // 每次请求的数据
        bSwiperLoadOff:[true,true],          // 切换页面是否加载数据
        bLoadOff:[true,true],                // 滚动是否加载数据
        busDetailNum:0,                      // 当前优惠券下标
        oswiperSlidMain:null,                // swiper主体
        time_Scroll:null,                    // 滚动加载定时器
        // 获取优惠券数据
        getDeatilData:function (index) {
            var _this = this;
            G_JSON_POST('/coupon/getGoodsDetailCoupons',{
                supplierId: supplierId,
                id: goodsId,
                goodsCategoryId: goodsCategoryId,
                type:index,
                pageNo:_this.paggerr[index]
            },function (data) {
                // console.log('couponData---店铺',index,data);
                if(data.status == 'success'){
                    var getData = data.supplierCoupons;     // 优惠券列表
                    if(getData && getData.length > 0){
                        // 我假设优惠券的面额为10的是平台券即couponNum == 10为平台券
                        if(getData != null && getData.length > 0){
                            oCouponList.eq(index).append(couponArea.couponHtml(getData));
                            _this.startNum[index] = _this.limit*_this.paggerr[index];
                            _this.paggerr[index]++;
                            oMoreBtnBox.eq(index).find('.js_loading').show();
                            // 当数据小于每次请求的数据时
                            if(getData.length < _this.limit){
                                // _this.bLoadOff[index] = false;
                                oMoreBtnBox.eq(index).find('.js_loadNull').hide();
                                oMoreBtnBox.eq(index).find('.js_loading').hide();
                            }

                            if(oCoupSwiper.height() > oCouponList.eq(index).height()){
                                // 如果容器的高度小于轮播区域的高度就要再加载一次
                                _this.startNum[index] = _this.limit*_this.paggerr[index];
                                _this.paggerr[index]++;
                                _this.getDeatilData(index);
                            }

                        }
                    }
                    // 数据是0 但不是第一页时
                    else if(getData == 0 && _this.paggerr[index] > 1){
                        _this.bLoadOff[index]  = false;
                        //把加载中隐藏，显示没有更多
                        oMoreBtnBox.eq(index).find('.js_loading').hide();
                        oMoreBtnBox.eq(index).find('.js_loadNull').show();
                        // return
                    }
                    // 数据是0  又是第一页时
                    else if(getData == 0 && _this.paggerr[index] < 2){
                        _this.bLoadOff[index]  = false;
                        _this.busDetailNum = 1;
                        _this.bSwiperLoadOff[0] = false;
                        oCouponList.eq(index).append(couponArea.nullCoupon());
                        // myPub.TipLayer('没有优惠券！');
                        oMoreBtnBox.eq(index).find('.js_loading').hide();
                        // return
                    }
                    else{
                        _this.bLoadOff[index]  = false;
                        oCouponList.eq(index).append(couponArea.nullCoupon());
                        _this.busDetailNum = 1;
                        _this.bSwiperLoadOff[0] = false;
                        // myPub.TipLayer('没有优惠券！');
                        oMoreBtnBox.eq(index).find('.js_loading').hide();
                        // return
                    }
                    getNow();   //启动立即领取可点
                    /*oCouponSeletSide.show().stop().animate({ 'bottom':0 },300,function() {
                        oShadow.show();
                        // bSideOff = true
                    });*/
                }else {
                    // bSideOff = true;
                    $('.js_couponList').eq(index).append(couponArea.nullCoupon());
                    myPub.TipLayer(data.msg);
                }
            });
        },

        // 滚动加载
        scrollAddData:function (index) {
          var _this = this;
          var minScrHeight = 50;
          var oCouponIntor = $('.js_couponIntor').eq(index);
          var oScroll = $('.js_scroll');
            oScroll.on('scroll',function () {
                var afterScroll = $(this).scrollTop();
                // 滚动距离页面底部200像素，延迟250毫秒加载
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function () {
                    if((oCouponIntor[0].scrollHeight - afterScroll - oScroll.height()) < minScrHeight){
                        if(_this.bLoadOff[_this.busDetailNum]){
                            // 滚动底部页数增加 起始数据等于上次结束数据  新的结束等于页数*页码数
                            _this.startNum[_this.busDetailNum] = _this.limit*_this.paggerr[_this.busDetailNum];
                            _this.paggerr[_this.busDetailNum]++;
                            _this.getDeatilData(_this.busDetailNum);
                        }
                    }
                },250)
            })
        },

        // 优惠券弹框切换
        couponSlider:function (NavName) {
            var oCoupSwiper = $('.js_coupSwiper');
            var oCoupNavUl = $('.js_coupNavUl');
            var oCouponIntor = $('.js_couponIntor');
            var _this = this;
            _this.oswiperSlidMain = oCoupSwiper.swiper({
                pagination: oCoupNavUl[0],
                paginationClickable: true,
                observer: true,
                observeParents: true,
                onInit: function (swiper) {
                    var index = swiper.activeIndex;
                    // oCouponIntor.hide().eq(index).show().css({'height': 'auto'});
                },
                paginationBulletRender:function(index,className){
                    //添加导航
                    return '<li class="Bflex1 '+className+'" data-type="'+index+'">'+ NavName[index] +'</li>';
                },
                onSlideChangeEnd: function (swiper) {
                    var index = swiper.activeIndex;
                    // var getHeight = oCouponIntor.eq(index).outerHeight(true);

                    oCouponIntor.hide().eq(index).show().css({'height': 'auto'});
                    _this.busDetailNum = index;
                    if(_this.bSwiperLoadOff[index]){
                        _this.bSwiperLoadOff[index] = false;
                        _this.getDeatilData(index);
                    }
                    // oWrap.stop().animate({scrollTop: oSildeNavUl_Top}, 10);
                    /*myPub.JudgeAppHide(function () {
                        //ios
                        window.webkit.messageHandlers.AppModel.postMessage({body: getHeight});
                    });*/
                }
            })
        },

        // 没有优惠券时的拼接html
        nullCoupon:function () {
            var shtml = '<div class="nullCoupon">'+
                        '   <div class="nullCouponImg">'+
                        '       <img src="/static_v4/image/wonderful/coupon-null.png" alt="">'+
                        '   </div>'+
                        '   <div class="">'+
                        '       <p>没有优惠券哦~</p>'+
                        '   </div>'+
                        '</div>';
            return shtml
        },

        // 拼接优惠券的Html
        couponHtml:function (data) {
            var shtml = '';
            for(var i=0; i<data.length; i++){
                if(data[i].supplierId == 0){
                    shtml += '<div class="coupon platCoupon" >'
                }else{
                    shtml += '<div class="coupon">'
                }
                shtml += '            <div class="couponBox" >' +
                    '                <div class="couponInfo HBox">' +
                    '                    <div class="couponInfoLeft HBox BoxCenter">' +
                    '                        <div class="couponPrice">' +
                    '                            <em>￥</em>' +
                    '                            <span>'+data[i].costPrice+'</span>' +
                    '                            <p>满'+data[i].needPrice+'元可用</p>' +
                    '                        </div>' +
                    '                    </div>' +
                    '                    <!--中间-->' +
                    '                    <div class="couponInfoCenter Bflex1 height_100">' +
                    '                        <div class="couponUseType">' +
                    '                            <h5 class="singleLine" >'+data[i].couponName+'</h5>' +
                    '                            <div class="tip_use" >' +
                    '                            </div>' +
                    '                            <div class="tip_useLimt Bflex1">' +
                    '                                <p>'+myPub.FormatDateTime(new Date(data[i].beginDate.time),"minDay",".")+"-"+myPub.FormatDateTime(new Date(data[i].endDate.time),"minDay",".")+'</p>' +
                    '                            </div>' +
                    '                        </div>' +
                    '                    </div>' ;
                if(data[i].isHasCoupon == 1){
                    shtml += '       <div class="couponInfoRight HBox BoxCenter">' +
                        '                 <div class="useThisCoupon HBox BoxCenter" data-couponId="'+ data[i].id +'">' +
                        '                        已领取' +
                        '                  </div>' +
                        '             </div>' ;
                }else {
                    shtml += '        <div class="couponInfoRight HBox BoxCenter">' +
                        '                   <div class="useThisCoupon">' +
                        '                        <button class="useThisCouponBtn HBox BoxCenter js_getNow" data-couponId="'+ data[i].id +'">立即领取</button>' +
                        '                        <div class="useThisCouponBtn HBox BoxCenter" data-couponId="'+ data[i].id +'">已领取</div>' +
                        '                   </div>' +
                        '              </div>' ;
                }


                shtml += '       </div>' +
                    '           </div>' +
                    '           <div class="gapBox gapBox_right">' +
                    '                <span class="gap gap_top"></span>' +
                    '                <span class="gap_line"></span>' +
                    '                <span class="gap gap_bot"></span>' +
                    '            </div>' +
                    '        </div>';
            }

            return shtml;
        }
    };

    couponArea.couponSlider(NavName);
    couponArea.getDeatilData(0);
    couponArea.scrollAddData(couponArea.busDetailNum);
});